<template>
	<view class="app-invite" :style="[AppSkinVar]">
		<e-loading-page :loading="loading"  >
			<template #icon>
				<loader ></loader>
			</template>
		</e-loading-page>
		<background-image :src="bgSrc" mode="aspectFill" :size="['100vw', '1448rpx']">
			<view class="invite-bg e-rela">
				<view class="qrcode-box e-abso">
					<view class="text-center c-primary e-m-b-20">
						{{ salt }}
					</view>
					<view class="text-center e-m-b-50">
						{{ $t('user.邀请码') }}
					</view>
					<view class="qrcode-box-code e-flex-xy-center bg-white">
						<!-- #ifndef MP-WEIXIN||MP-ALIPAY -->
						<e-qrcode v-if="shareUrl" :text="shareUrl" :size="120"></e-qrcode>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN||MP-ALIPAY -->
						<image :src="$fullLink(shareUrl)"></image>
						<!-- #endif -->
					</view>
				</view>
				<view class="total-box e-abso e-flex bg-white">
					<view class="e-flex e-p-l-20">
						<load-image mode="aspectFill" :size="['84rpx']" shape="circle" :src="userInfo.photo">
							<template #error>
								<app-image mode="aspectFill" :size="['50rpx']" shape="circle" src="default-headerImg.png" ></app-image>
							</template>
						</load-image>
						<view class="e-flex-1 e-m-l-20">
							<view class="name-box e-line-1 fw-500">
								{{ userInfo.nickname || '' }}
							</view>
							<view class="e-font-24 e-m-t-8 c-98">
								{{ $t('user.邀您扫码注册') }}
							</view>
						</view>
					</view>
					<!-- <view class="text-center" @tap="$goTo('/pages/user/inviteInfo')">
						<view class="c-primary fw-600">
							<text class="e-font-48">{{ total }}</text>
							<text>{{ $t('user.人') }}</text>
						</view>
						<view class="e-font-26 e-m-t-8 c-4d fw-500">
							{{ $t('user.成功邀请') }}
						</view>
					</view> -->
				</view>
			</view>
		</background-image>
		<view class="ios-btm"></view>
		<view class="canvas-box e-abso">
			<canvas ref="canvas" class="invitecode-canvas" id="invitecode-canvas" canvas-id="invitecode-canvas"></canvas>
		</view>
		<view class="fixed-bottom bg-white" style="z-index: 2">
			<view class="button-box e-flex e-p-30 bg-white">
				<button class="c-primary border-primary bg-white e-flex-xy-center e-m-r-60" @tap="$copy(salt)">
					<text>{{ $t('user.复制邀请码') }}</text>
				</button>
				<button class="bg-primary c-white e-flex-xy-center" @tap="invite">
					<text>{{ $t('user.分享邀请好友') }}</text>
				</button>
			</view>
		</view>

		<view class="txt-button text-center c-white e-font-32" v-if="txtShow" @tap="$goTo('/pages/invite/txt')">
			{{ $t('user.规则') }}
		</view>
		<!-- #ifdef H5 -->
		<invite-popup :show="popupShow" :url="mpShareUrl" @close="popupShow = false"></invite-popup>
		<!-- #endif -->
	</view>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
// 所有可被装修选中的页面的混入，用于动态修改标题，例如装修的按钮组组件，按钮的文本为xxx，跳转到对应页面时，会将页面的标题修改为xxx
import layoutPageTitleMixIn from '@/common/mixin/layoutPageTitleMixIn';
export default defineComponent({
	mixins: [layoutPageTitleMixIn]
});
</script>
<script setup lang="ts">
import { ref } from 'vue'
import { getInviteData } from '@/common/request/api'
import {
	drawQuadrilateral, drawQRCode, drawRoundedRectangle, drawBorderImage, drawText, drawArrowRectangle, getTextLineHeight
} from '@/common/canvas'
/* 引入uqrcode核心js */
import { uQRCode, getAppImageInfo,isObj } from '@/common/utils'
import { useUser,useInit } from '@/common/stores'
import { storeToRefs } from 'pinia'
import {
	useCurrentInstance,
	useCanvas
} from '@/common/hooks'
import {
	onShow
} from '@dcloudio/uni-app'
// #ifdef H5
import invitePopup from './child/invite-popup.vue'
// #endif

const ctx = useCurrentInstance()
const { userInfo, } = storeToRefs(useUser())
const { canvasdraw, canvasImgUrl: mpShareUrl } = useCanvas()
const { AppSkin } = storeToRefs(useInit());

const loading = ref(false)
const bgSrc = ref('')
const total = ref(0)
const popupShow = ref(false)
const txtShow = ref(false)
const shareUrl = ref('')
const salt = ref('')

onShow(() => {
	let scene = ctx.$getShareUrlScene('')
	// #ifdef PRIVATE
	scene = scene + `&storeId=${uni.getStorageSync('storeId')}`
	// #endif
	getInviteData({
		// #ifdef MP-WEIXIN||MP-ALIPAY || SUBSCRIPTION || PRIVATE
		url: '',
		// pages/public/account/register
		// #endif
		// #ifdef HTML5 || PREVIEW
		url: '/pages/public/account/register',
		// #endif
		// #ifdef APP-PLUS
		url: '/pages/invite/register',
		// #endif
		// #ifdef  PREVIEW
		templateId: uni.getStorageSync('templateId'),
		// #endif
		// #ifdef  PRIVATE
		formType: 'mp_private'
		// #endif
		// #ifndef  PRIVATE
		formType: getApp().globalData.payFromType
		// #endif
		// #ifdef SUBSCRIPTION || PRIVATE
		,
		scene
		// #endif
	}).then(res => {
		if (res.global) {
			let url = ctx.$fullLink(res.global.backLogo)
			bgSrc.value = url
			make(url, res.shareUrl, res.salt)
			txtShow.value = res.global.backState === 1
		}
		total.value = res.shareCount
		// #ifdef APP
		uni.sendNativeEvent(
			'appShare',
			{
				msg: 'sendShareData',
				
			},
			(ret:any) => {
				if(!isObj(ret)){
					ret = JSON.parse(ret)
				}
				if (ret.global) {
					let url = ctx.$fullLink(ret.global.backLogo)
					bgSrc.value = url
					ret.shareUrl = `${ret.shareUrl}${ret.shareUrl.indexOf('?') > -1 ? '&':'?' }otherTenant=${uni.getStorageSync('tenant')}`
					make(url, ret.shareUrl, ret.salt)
					txtShow.value = ret.global.backState === 1
				}
				total.value = ret.shareCount
			}
		);
		// #endif
	}).finally(() => {
		loading.value = false
	})
	

})



const make = async (bgUrl : string, _shareUrl : string, _salt : string) => {
	shareUrl.value = _shareUrl
	salt.value = _salt
	canvasdraw({
		bgImgUrl: bgUrl,
		canvasId: 'invitecode-canvas',
		that: ctx,
		width: 750,
		height: 1448,
		bgWidth: 750,
		bgHeight: 1448,
		drawIng: async (canvasCtx) => {
			canvasCtx.setFontSize(32);
			let { textHeight, row: textList } = getTextLineHeight(canvasCtx, {
				w: 180,
				text: _salt,
			})
			let saltHeight = textHeight + 44
			textList.forEach((item, index) => {
				drawText(canvasCtx, {
					x: 375,
					y: 452 + (index + 1) * 44,
					text: item,
					size: 32,
					font: 'normal normal bold 32px',
					fillStyle: AppSkin.value.primary,
					align: 'center'
				})
			})
			drawText(canvasCtx, {
				x: 375,
				y: 472 + saltHeight,
				text: ctx.$t('user.邀请码'),
				size: 24,
				font: 'normal normal bold 24px',
				align: 'center'
			})
			// 底部用户信息边框
			drawRoundedRectangle(canvasCtx, {
				x: 30,
				y: 1222,
				width: 690,
				height: 188,
				radius: 20
			})


			let name = userInfo.value.nickname || ''
			if (name.length > 11) {
				name = `${name.slice(0, 11)}...`
			}

			drawText(canvasCtx, {
				x: 182,
				y: 1308,
				text: name,
				size: 28,
				font: 'normal normal bold 28px'
			})
			drawText(canvasCtx, {
				x: 182,
				y: 1350,
				text: ctx.$t('user.邀您扫码注册'),
				size: 24,
				fillStyle: '#989898',
				font: 'normal normal normal 24px'
			})
			// 带箭头的矩形
			drawArrowRectangle(canvasCtx, {
				x: 416,
				y: 1260,
				width: 266,
				height: 112,
				radius: 5,
				strokeStyle: ctx.AppSkin.primary,
				lineWidth: 4
			})
			drawText(canvasCtx, {
				x: 456,
				y: 1308,
				text: ctx.$t('user.邀请好友注册'),
				size: 26,
				fillStyle: ctx.AppSkin.primary,
				font: 'normal normal normal 26px'
			})
			drawText(canvasCtx, {
				x: 456,
				y: 1350,
				text: ctx.$t('user.好友消费就得奖励'),
				size: 26,
				fillStyle: ctx.AppSkin.primary,
				font: 'normal normal normal 26px'
			})
			// 小程序绘制二维码
			// #ifdef MP-WEIXIN||MP-ALIPAY
			let codePath = await getAppImageInfo(ctx.$fullLink(_shareUrl))
			if (codePath.path) {
				canvasCtx.drawImage(codePath.path, 256, 584 + saltHeight, 240, 240)
			}

			// #endif
			// #ifndef MP-WEIXIN||MP-ALIPAY
			// 非小程序绘制二维码
			// 二维码的边框
			drawQuadrilateral(canvasCtx, {
				// r: 112,
				x: 216,
				y: 554 + saltHeight,
				width: 300
			})
			drawQRCode(canvasCtx, {
				x: 256,
				y: 584 + saltHeight,
				size: 240, //二维码大小
				margin: 0, // 填充边距
				modules: uQRCode.getModules({
					id: 'invitecode-canvas', //canvasId
					mode: 'canvas', // 生成模式
					size: 240, //二维码大小
					margin: 0, // 填充边距
					backgroundColor: '#fff', // 背景色
					foregroundColor: '#000', // 前景色
					errorCorrectLevel: uQRCode.errorCorrectLevel.H ,// 纠错等级,
					text: _shareUrl
				})
			})
			// #endif
			try{
				let photoRes = await getAppImageInfo(ctx.$fullLink(userInfo.value.photo))
				let photo = photoRes.path
				// drawBorderImage使用了clip裁剪函数，需放到最后绘制，否则会影响文本的绘制
				if (photo) {
					drawBorderImage(canvasCtx, {
						x: 78,
						y: 1278,
						width: 84,
						height: 84,
						radius: 42,
						imgOption: {
							url: photo,
							x: 78,
							y: 1278,
							w: 84
						}
					})
				}
			}catch(e){
				//TODO handle the exception
			}
			


		}
	})

}
const invite = () => {
	// #ifdef H5
	popupShow.value = true
	// #endif
	// #ifdef APP-PLUS
	mpShareUrl.value&&uni.saveImageToPhotosAlbum({
		filePath: mpShareUrl.value
	}).then(() => {
		ctx.$toast(ctx.$t('user.保存相册成功'));
	});
	// ctx.$goTo('/pages/invite/AppInvite', { url: mpShareUrl.value })
	// #endif
	// #ifdef MP-WEIXIN
	wx.showShareImageMenu({
		path: mpShareUrl.value
	})
	// #endif
}
</script>

<style lang="scss" scoped>
.c-4d {
	color: #4d4d4d;
}

.c-98 {
	color: #989898;
}
@include appBem_b(invite) {
	padding-bottom: 160rpx;
	.invite-bg {
		// width: 100vw;
		height: 1448rpx;

		.name-box {
			width: 200rpx;
		}

		.qrcode-box {
			width: 380rpx;
			top: 32.46%;
			left: calc(50% - 190rpx);

			&-code {
				margin-left: 40rpx;
				width: 300rpx;
				height: 300rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			// .salt-box {
			// 	width: 380rpx;
			// 	background: #fdfbf8;
			// 	border-radius: 10rpx;
			// 	border: 2rpx solid #fce4bb;
			// 	padding: 10rpx 34rpx;
			// }
		}

		.total-box {
			width: calc(100% - 60rpx);
			height: 188rpx;
			border-radius: 20rpx;
			left: 30rpx;
			bottom: 38rpx;
			padding: 0 26rpx;

			> view {
				flex: 0 0 50%;
				width: 50%;
			}

			.photo {
				border-radius: 50%;
			}
		}
	}

	.canvas-box {
		left: -9999px;
		top: -9999px;

		.invitecode-canvas {
			width: 750px;
			height: 1448px;
			font-kerning: normal;
		}
	}

	.button-box {
		height: 160rpx;

		.border-primary {
			border: 2rpx solid var(--color-primary);
		}

		button {
			width: 100%;
			height: 100%;
			font-size: 28rpx !important;
			font-weight: 500;
			letter-spacing: 2rpx;
			border-radius: 50rpx;
		}
	}

	.txt-button {
		position: fixed;
		top: 376rpx;
		right: 0;
		padding: 0 30rpx;
		height: 70rpx;
		line-height: 70rpx;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 200rpx 0rpx 0rpx 200rpx;
	}
}
</style>
